<template>
  <div class="app-container">
    <el-row>
      <!-- 搜索区域 -->
      <el-card style="margin:0 0 5px 5px" v-show="showSearch">
        <el-form ref="queryForm" :inline="true" :model="queryData">
          <el-form-item label="爬虫名称" prop="Q_name_S_LK">
            <el-input v-model="queryData.Q_name_S_LK" placeholder="爬虫名称" />
          </el-form-item>
          <el-form-item class="m-l-20">
            <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- table区域 -->
      <el-card class="m-l-5">
        <el-row :gutter="10" class="m-b-5">
          <el-col :span="1.5">
            <el-button v-permission="['spider:program:add']" size="mini" plain type="primary" icon="el-icon-plus" @click="handleInfo()">
              新增爬虫
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button size="mini" plain type="success" @click="handleDocument()">
              说明文档
            </el-button>
          </el-col>
          <table-toolbar :showSearch.sync="showSearch" @refresh="getTableData" />
        </el-row>
        <el-table
          ref="spider_table"
          v-loading="tableLoading"
          row-key="id"
          :data="tableData"
          element-loading-text="加载中"
          border
          fit
          highlight-current-row
          show-overflow-tooltip
          height="100px"
          v-el-height-adaptive-table="{bottomOffset: 110}"
        >
          <el-table-column align="center" label="序号" width="55" :formatter="getDataIndex" />
          <el-table-column align="center" label="爬虫名称" show-overflow-tooltip>
            <template slot-scope="scope">
              <span style="cursor: pointer" @click="handleInfo(scope.row.id)">{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="cron" width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              <span style="cursor: pointer" @click="handleCron(scope.row)">{{ getCron(scope.row.cron) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="定时/长任务" width="110">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enabled"
                active-value="1"
                inactive-value="0"
                @change="handleSwitch(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="创建时间" prop="createDate" width="180" show-overflow-tooltip />
          <el-table-column align="center" label="上次执行时间" prop="lastExecuteTime" width="180" show-overflow-tooltip />
          <el-table-column align="center" label="运行中/已完成" width="150">
            <template slot-scope="scope">
              <el-tag :type="getSpiderColor(scope.row)" v-text="getSpiderType(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="下次执行时间" prop="nextExecuteTime" width="160" show-overflow-tooltip />
          <el-table-column align="center" label="操作" width="110" fixed="right">
            <template slot-scope="scope">
              <el-dropdown>
                <span class="el-dropdown-link">
                  选项<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-permission="['spider:program:edit']">
                    <el-link :underline="false" type="primary" icon="el-icon-edit-outline" @click="handleInfo(scope.row.id)">编辑</el-link>
                  </el-dropdown-item>
                  <el-dropdown-item v-permission="['spider:program:edit']">
                    <el-link :underline="false" type="warning" icon="el-icon-warning-outline" @click="handleNotice(scope.row.id)">通知设置</el-link>
                  </el-dropdown-item>
                  <el-dropdown-item v-permission="['spider:program:edit']">
                    <el-link :underline="false" type="success" icon="el-icon-video-play" @click="handleRun(scope.row.id)">手动运行</el-link>
                  </el-dropdown-item>
                  <el-dropdown-item v-permission="['spider:program:edit']">
                    <el-link :underline="false" icon="el-icon-document" @click="handleLog(scope.row.id)">日志</el-link>
                  </el-dropdown-item>
                  <el-dropdown-item v-permission="['spider:program:delete']">
                    <el-link :underline="false" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-link>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData" />
      </el-card>
    </el-row>

    <spider-form-dialog v-if="openFormDialog" ref="spiderForm" :title="title" :fullscreen="fullscreen" @confirmForm="handleFilter" />
    <spider-notice-dialog v-if="openNoticeDialog" ref="noticeDialog" />
    <el-dialog title="Cron表达式生成器" :visible.sync="openCronDialog" append-to-body class="scrollbar" destroy-on-close>
      <crontab @hide="openCronDialog=false" @fill="crontabFill" :expression="expression"></crontab>
    </el-dialog>
  </div>
</template>

<script>
import { spiderTable, spiderRun, spiderCron, spiderDelete } from '@/api/tool/spider'
import Crontab from '@/components/Crontab'
import SpiderFormDialog from './form/dialog'
import SpiderNoticeDialog from './form/notice'

export default {
  components: {
    Crontab,
    SpiderFormDialog,
    SpiderNoticeDialog
  },
  data() {
    return {
      showSearch: true,
      queryData: {
        Q_name_S_LK: undefined
      },
      tableLoading: false,
      tableData: [],
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      },
      title: '可视化爬虫工具',
      fullscreen: false,
      selected: undefined,
      expression: undefined,
      openFormDialog: false,
      openCronDialog: false,
      openNoticeDialog: false
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.getTableData()
    },
    getSpiderType(row) {
      const running = row.running | 0
      const count = row.executeCount | 0
      return running + '/' + count
    },
    getSpiderColor(row) {
      if (row.running) {
        return 'primary'
      }
      return 'info'
    },
    getCron(cron) {
      return cron || '选择表达式'
    },
    getDataIndex(row, column, cellValue, index) {
      return index + 1
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getTableData()
    },
    handleClear() {
      this.$refs.queryForm.resetFields()
      this.getTableData()
    },
    getTableData() {
      const query = Object.assign(this.tableQuery, this.queryData)
      this.tableLoading = true
      spiderTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
        this.$refs.spider_table.bodyWrapper.scrollTop = 0
      }).catch(e => {
        this.tableLoading = false
      })
    },
    handleCron(row) {
      this.selected = row.id
      this.expression = row.cron
      this.openCronDialog = true
    },
    crontabFill(value) {
      spiderCron(this.selected, value).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.handleFilter()
      })
    },
    handleSwitch(row) {
      if (!row.cron) {
        this.$modal.msgWarning('请先添加cron表达式')
        return
      }
      let url = `${process.env.VUE_APP_MODULE_ADMIN_API}/api/spider/flow/`
      let message = '切换为'
      if (row.enabled === '1') {
        url = url + 'start/'
        message = message + '定时任务'
      } else {
        url = url + 'stop/'
        message = message + '长任务'
      }
      url = url + row.id
      this.$http.post(url).then(response => {
        this.handleFilter()
        this.$modal.msgSuccess(message + '成功!')
      }).catch(e => {})
    },
    handleInfo(id) {
      this.fullscreen = true
      this.openFormDialog = true
      let url = this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/api/spider/flow/editor/html?access_token=` + this.$store.state.user.token
      if (id) {
        url += '&id=' + id
      }
      this.$nextTick(() => {
        this.$refs.spiderForm.init(url)
      })
    },
    handleDocument() {
      window.open('https://www.spiderflow.org/intro.html')
    },
    handleNotice(id) {
      this.openNoticeDialog = true
      this.$nextTick(() => {
        this.$refs.noticeDialog.init(id)
      })
    },
    handleRun(id) {
      this.$confirm('您确定要手动运行一次该爬虫吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        spiderRun(id).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response.msg)
        }).catch(e => {})
      }).catch(e => {})
    },
    handleLog(id) {
      window.open(this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/api/spider/flow/log/download?access_token=` + this.$store.state.user.token + '&id=' + id)
    },
    handleDel(id) {
      this.$confirm('是否删除所选数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        spiderDelete(id).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response.msg)
        }).catch(e => {})
      }).catch(e => {})
    }
  }
}
</script>

<style scoped>
.line{
  text-align: center;
}
</style>
